package com.topone.controller;

import com.topone.Converter.BussinessForm2OBussinessDTOConvert;
import com.topone.Enum.BussinessStatusEnum;
import com.topone.Enum.ShopApplyStatusEnum;
import com.topone.Exception.FanZoneException;
import com.topone.Form.BussinessForm;
import com.topone.Utils.CodeUntil;
import com.topone.Utils.KeyUntil;
import com.topone.config.UploadConfig;
import com.topone.dataObject.Bussiness;
import com.topone.dataObject.ShopApply;
import com.topone.service.BussinessService;
import com.topone.service.ShopApplyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.Valid;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;

/**
 * Created by Administrator on 2018/2/4,0004.
 */
@Controller
@RequestMapping("/seller/bussiness")
@Slf4j
public class SellBussinessController {

    @Autowired
    private BussinessService bussinessService;

    @Autowired
    private ShopApplyService shopApplyService;
    @Autowired
    private UploadConfig uploadConfig;


    @GetMapping("/create")
    public ModelAndView create(@RequestParam(value="bussinessCode",defaultValue ="")
                                       String bussinessCode,
                               Map<String,Object> map){
        map.put("bussinessCode",bussinessCode);
        return new ModelAndView("bussiness/create",map);
    }

    @GetMapping("/list")
    public  ModelAndView list( @RequestParam(value="page",defaultValue = "1")   Integer page,
                               @RequestParam(value = "size",defaultValue = "10")   Integer size,
                               Map<String, Object> map){
        PageRequest request = new PageRequest(page-1, size);
        Page<Bussiness> bussinessPage=bussinessService.findUpAll(
                BussinessStatusEnum.suceess.getCode(),request);

        map.put("currentPage",page);
        map.put("size",size);
        map.put("bussinessPage",bussinessPage);
        return new ModelAndView("bussiness/list",map);
    }
    @GetMapping("/detail")
    public ModelAndView index(@RequestParam("bussinessCode") String bussinessCode,
                              @RequestParam(value="page",defaultValue = "1")   Integer page,
                              @RequestParam(value = "size",defaultValue = "10")   Integer size,
                              Map<String, Object> map){
        if(!StringUtils.isEmpty(bussinessCode)){
            PageRequest pageRequest=new PageRequest(page-1,size);
            Page<Bussiness> bussinessPage=bussinessService.findList(bussinessCode,pageRequest);
            map.put("bussinessPage",bussinessPage);
            map.put("bussinessCode",bussinessCode);
            map.put("currentPage",page);
            map.put("size",size);
        }
        return new ModelAndView("bussiness/detail",map);
    }

    @GetMapping("/close")
    public ModelAndView close(@RequestParam("bussinessId") String bussinessId,
                              @RequestParam("bussinessCode") String bussinessCode,
                              Map<String,Object> map){

        Bussiness bussiness=bussinessService.findOne(bussinessCode,bussinessId);

        if(bussiness!=null){
            bussiness.setBussinessStatus(BussinessStatusEnum.LEFT.getCode());
            bussinessService.save(bussiness,null);
            map.put("msg","关店成功");
            map.put("url","/fanZone/seller/bussiness/detail?bussinessCode="+bussinessCode);
        }
        log.info("【后台申请关店】成功,{}",map);
        return new ModelAndView("common/success",map);
    }
    @PostMapping("/save")
    public ModelAndView backSave(@Valid BussinessForm bussinessForm,
                                 BindingResult bindingResult,
                                 MultipartHttpServletRequest multiReq,
                                 Map<String,Object> map){
        if(bindingResult.hasErrors()){
            log.error("【后台商家入驻】参数不正确,bussinessForm={}",bussinessForm);
            map.put("msg",bindingResult.getFieldError().getDefaultMessage());
            map.put("url","/fanZone/seller/bussiness/list");
            return new ModelAndView("common/error",map);
        }

        //处理上传文件
        // 获取上传文件的路径
        String uploadBussinessImgPath = uploadConfig.getBussinessImgPath();
        // 截取上传文件的文件名
        String uploadBussinessImgName = UUID.randomUUID().toString()
                .replace("-","");
        ///截取上传文件的后缀
        String originalName=multiReq.getFile("file").getOriginalFilename();
        String fileType=originalName
                .substring(originalName.indexOf('.') + 1, originalName.length());
        //文件全路径
        String filePath=uploadBussinessImgPath+uploadBussinessImgName+"."+fileType;
        FileOutputStream fos=null;
        FileInputStream fis=null;
        try {
            File file = new File(uploadBussinessImgPath);
            if(!file.exists()){   //商家图片路径不存在，创建路径
                file.mkdirs();
            }
            fis=(FileInputStream) multiReq.getFile("file").getInputStream();
            fos = new FileOutputStream(new File(filePath));
            long size=fis.available();
            if(size>104865760){  //上传最大限制10M
                log.error("【后台申请商家入驻】上传文件过大");
                map.put("msg","上传文件过大");
                map.put("url","/fanZone/seller/bussiness/list");
                return  new ModelAndView("common/error",map);
            }

            byte[] data=new byte[fis.available()];
            fis.read(data);
            fos.write(data);
        }catch (IOException e){
            log.error("【后台申请商家入驻】异常, {}",e);
            map.put("msg",e);
            map.put("url","/fanZone/seller/bussiness/list");
            return  new ModelAndView("common/error",map);
        }finally {
            try {
                if(fis!=null) {
                    fis.close();
                }
                if (fos!=null) {
                    fos.close();
                }
            }catch (IOException e){
                log.error("【后台申请商家入驻】异常, {}",e);
                map.put("msg",e);
                map.put("url","/fanZone/seller/bussiness/list");
                return  new ModelAndView("common/error",map);
            }
        }

        ShopApply shopApply=null;
        Bussiness bussiness = BussinessForm2OBussinessDTOConvert
                .convert(bussinessForm);
        //后台新增店铺或者添加分店
        if(StringUtils.isEmpty(bussiness.getBussinessId())){
            if(StringUtils.isEmpty(bussiness.getBussinessCode())){
                bussiness.setBussinessCode(CodeUntil.getBussinessCode());
            }
            bussiness.setBussinessId(KeyUntil.getUniqueKey());
            bussiness.setBussinessStatus(BussinessStatusEnum.suceess.getCode());
        }else{
            //shopapply申请店铺入驻
            bussiness.setBussinessCode(CodeUntil.getBussinessCode());
            bussiness.setBussinessStatus(BussinessStatusEnum.suceess.getCode());
            //修改shopApply的状态 待入驻-->已入驻
            shopApply=shopApplyService.findOne(bussiness.getBussinessId());
            if(shopApply.getApplyStatus()== ShopApplyStatusEnum.WAIT.getCode()){
                shopApply.setApplyStatus(ShopApplyStatusEnum.SUCCESS.getCode());
            }
        }
        //保存数据
        try {
            bussinessService.save(bussiness,shopApply);
        }catch (FanZoneException e){
            map.put("msg",e.getMessage());
            map.put("url","/fanZone/seller/bussiness/detail?bussinessCode="+bussiness.getBussinessCode());
            return  new ModelAndView("common/error",map);
        }
        map.put("msg","商家入驻成功");
        map.put("url","/fanZone/seller/bussiness/detail?bussinessCode="+bussiness.getBussinessCode());
        return new ModelAndView("common/success",map);
    }


}
